var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var WxParse = require('../../wxParse/wxParse.js');
var base64 = require('../../utils/Base64.js');
var topictitle ="";
var topicid = "";
var app = getApp();
var uid = '';
var uname = '';  //作者用户名
var wxAuthFail = true;
var inviteuid = 0;
var linkcode = '';

var detailMessage = '';

Page({
  data: {
    util: util,
    host: util.api_host,
    tc: 0,
    my_cion: 88,

    indicatorDots: true,
    autoplay: true,
    interval: 4000,
    duration: 600,
    swiper_w:0,
    swiper_h:0,

    video_w: 300,
    video_h: 165,

    detailShouhou: '',//售后保障
    
      data:{},
      likeuser: [],
      detailMessage: '',
      pinHistoryData:[], //拼单历史
      imgDomain: app.globalData.imgDomain,
      isFollow: false, //是否已关注
      isLiked: false, //是否已赞
      uid:'',  //当前登录用户Id
      token:'', //post请求时，当前登录用户token
      loginUname:'', //当前登录用户名
      commentMsg : '',
      replyid:0, //当前被回复的评论id
      openid:'',
      topicid:0,
      startTime: 0,
      hasShare: false,
      tuid:0,
      firstImgUrl:'',
      canEdit: false,
      isShow: false,

      isIphone: false,

      isOnLoad:false,

      modalHidden: true,

      guigeData: [],
      selectGuige: '',

      gwc_count: 0,

      countValue: 1,

      curr: {
        goods_info:"curr",
        pinglun: "",
        shouhou: ""
      },

      contact_phone: '',

      commentList: [],
      colorSet: '',

      ghs_info: ''
  },
  
  onLoad: function(data){
    wx.showLoading({
      title: '加载中',
      mask: 'true'
    });
    var tc = app.get_tc();
    var titlename = tc == 1 ? '詳情' : '详情';
    wx.setNavigationBarTitle({
      title: titlename,
    });
    this.getYunfeiSet();
    var that = this;
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
    });
    wx.getSystemInfo({
      success: function (res) {
        var isiPhone = (res.model.indexOf('iPhone') >= 0);
        // var height = res.windowWidth * 2 / 3;
        var height = res.windowWidth;
        var v_w = res.windowWidth;
        // v_w =  v_w - 25;
        var v_h = v_w * 4/ 7;
        that.setData({
          isIphone: isiPhone,
          swiper_w: res.windowWidth,
          swiper_h: height,
          video_w: v_w,
          video_h: v_h,
          goodsImgView_h: (res.windowWidth - 30) / 2,
          tc: tc
        });
      }
    })

    var gwc_datas = wx.getStorageSync('gwc_datas');
    if (!gwc_datas) {
      gwc_datas = [];
    }
    this.setData({
      gwc_count: gwc_datas.length
    });

    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "wxcheck",
        "tc": that.data.tc
      },
      success: function (responseData) {
        that.setData({
          isShow: responseData.data.isShow
        });
      }
    });

    topicid = data.topicid || "";
    //是否是从 别人分享的 页面点进来的
    inviteuid = data.inviteuid ? data.inviteuid : '';
    var pages = getCurrentPages();
    var curPageIndex = pages.length;
    //如果是分享进来 或者 当前栈下标 是 1 都认为是分享进来的  因为分享人可能没授权登录 无法分享邀请码
    var isShare = (inviteuid || curPageIndex <= 1);
    this.setData({
      hasShare: isShare,
      topicid: topicid,
      isOnLoad: true
    })
    
    //获取商品32位唯一id，用户商品三级分销
    linkcode = data.linkcode ? data.linkcode : '';
    //调用应用实例的方法获取全局数据
    that.getLoginInfo();
    //获取售后保障
    // this.getShouhouMsg();

    // this.load();

    app.getAllAbout('contact', function (res) {
      that.setData({
        contact_phone: res
      })
    });
  },

  onShow:function(){
    // if(!this.data.isOnLoad){
    //   this.load();
    // }
    this.setData({
      isOnLoad: false,
    })
  },

  //获取售后保障介绍
  getShouhouMsg: function(){
    var that = this;
    
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "shouhou",
        "uid": util.orgid
      },
      success: function (responseData) {
        console.log("售后保障：", responseData);
        that.setData({
          detailShouhou: responseData.data.msg,
        });
        /** 
        * WxParse.wxParse(bindName , type, data, target,imagePadding) 
        * 1.bindName绑定的数据名(必填) 
        * 2.type可以为html或者md(必填) 
        * 3.data为传入的具体数据(必填) 
        * 4.target为Page对象,一般为this(必填) 
        * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选) 
        */
        WxParse.wxParse('detailShouhou', 'html', that.data.detailShouhou, that, 12); 
      }
    });
  },

  changeContent: function(e){
    var tag = e.currentTarget.dataset.tag;
    if (tag == 'gi') {
      this.setData({
        curr: {
          goods_info: "curr",
          pinglun: "",
          shouhou: ""
        }
      })
    } else if (tag == 'pl'){
      this.setData({
        curr: {
          goods_info: "",
          pinglun: "curr",
          shouhou: ""
        }
      })
    } else if (tag == 'sh'){
      this.setData({
        curr: {
          goods_info: "",
          pinglun: "",
          shouhou: "curr"
        }
      })
    }
  },

  load:function(){
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topicdetail",
      linkcode: linkcode,
      inviteuid: inviteuid,
      loginuid: that.data.uid ? that.data.uid : '',
      topicid: topicid
    };
    console.log("动态详情请求参数：", params);
    //动态详情
    util.api({
        data:params,
        success:function(responseData){  
            var data = responseData.data;
            console.log("啊啊啊啊啊详情：", data);

            if (uid == data.user.uid) {
              that.setData({
                canEdit: true
              })
            }
            //获取规格商品
            that.getGuigeData(data.id);

            //供货商信息
            if (data.orgid) {
              app.GetUserInfo(data.orgid, function (res) {
                console.log("供货商信息：", res);
                that.setData({
                  ghs_info: res
                })
              });
            }

            //处理时间
            var date = new Date(data.dateline*1000);
            data.formatDate = date.getFullYear()+"-"+(Number(date.getMonth())+1)+"-"+date.getDate();
            //处理语音
            if(data.audio) {                
                data.formatAudio = JSON.parse(data.audio);
            }
            //处理视频
            if (data.video) {
              var videolinks = data.video.split(",");
              var len = videolinks.length;
              var tx_videolinks = [];
              for (var i = 0; i < len; i++) {
                if (videolinks[i].indexOf('v.qq.com') > 0) {
                  tx_videolinks = tx_videolinks.concat(videolinks[i])
                }
              }
              len = tx_videolinks.length;
              var videoSrcs = new Array(len);
              var count = 0;
              for (var i = 0; i < len; i++) {
                app.getVideoSrcLink(i, tx_videolinks[i], function (url, index) {
                  count++;
                  if (url != -1) {
                    videoSrcs[index] = url;
                  }
                  if (count >= len) {
                    var videoSrcArr = [];
                    for(var n = 0; n < len; n++){
                      if(videoSrcs[n]){
                        videoSrcArr = videoSrcArr.concat(videoSrcs[n]);
                      }
                    }
                    that.setData({
                      videolinkArray: videoSrcArr
                    });
                  }
                  
                });
              }
            }
            //处理message  
            detailMessage = data.message;
            // detailMessage = data.message.replace(/\n/g, '<br />');
            console.log("detailMessage: ", detailMessage);
            
            that.setData({
              detailMessage: data.message,
            }); 
            /** 
            * WxParse.wxParse(bindName , type, data, target,imagePadding) 
            * 1.bindName绑定的数据名(必填) 
            * 2.type可以为html或者md(必填) 
            * 3.data为传入的具体数据(必填) 
            * 4.target为Page对象,一般为this(必填) 
            * 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选) 
            */
            WxParse.wxParse('detailMessage', 'html', detailMessage, that, 12); 
            // data.message = data.message.replace(/&nbsp;/g, '');
            
            topictitle = data.topictitle;
            uname = data.user.username;
            
            var f_imgUrl = '';
            if (data.photoscbk && data.photoscbk.length > 0){
              var firstImageInfo = data.photoscbk[0];
              if (firstImageInfo) {
                f_imgUrl = firstImageInfo.photo + "!120a";
              }
            }
            console.log("第一张图片链接：", f_imgUrl);
            that.setData({
                data:data,
                likeuser: data.likeuser,
                isLiked:data.isLiked,
                tuid:data.postuid,
                firstImgUrl: f_imgUrl
            });          
           //当前用户是否已关注作者
            that.isFollow(uid, data.postuid);
            //当前用户是否已赞该动态
            that.isLike(uid);
            wx.hideLoading();
        }
    });
    //拼单列表
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"getgoodspin",
            goods_id:topicid,
        },
        success:function(responseData){                 
            var data = responseData.data;
            console.log("历史拼单：", data);
            if(!data.msg){
              var keys = [];
              for (var key in data) {
                keys.push(key);
              }
              var pinArray = [];
              var index = 0;
              for (var i = keys.length - 1; i >= 0; i--) {
                pinArray[index] = [];
                pinArray[index] = data[keys[i]];
                index++;
              }
              console.log("历史拼单array：", pinArray);
              if (pinArray.length > 0) {
                that.setData({
                  pinHistoryData: pinArray
                });
              }  
            }           
        }
    });
    
    this.loadCommentList(topicid, 1);
  },

  //读取所有评论
  loadCommentList: function(gid, page){
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "ordercommentall",
        goods_id: gid,
        page: page,
        num:10
      },
      success: function (responseData) {
        var data = responseData.data;
        console.log("商品评论：", data);
        if (data && data.length > 0) {
          data.forEach(function (m, i) {
            m.pinglun.date = util.formatTime(new Date(parseInt(m.pinglun.dateline) * 1000), '-', ':');
          });
          that.setData({
            commentList: data
          });
        }
      }
    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },
  getLoginInfo:function(){
    var that = this;
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        
        //更新数据
        wxAuthFail = false;
        uid = res.uid;
        that.setData({
          uid: res.uid,
          token: res.token,
          loginUname: res.uname,
          openid: res.wxsmall_openid
        })

        that.load();

        var canEdit = false;
        if (that.data.data && that.data.data.user && res.uid == that.data.data.user.uid) {
          canEdit = true;
        }
        //设置用户信息
        app.GetUserInfo(res.uid, function (u_res) {
          console.log("getUserInfo:", u_res);
          //更新数据
          that.setData({
            canEdit: canEdit ? canEdit : u_res.isgroup == 1
          })
        });
      } else {
        that.load();
        wxAuthFail = true;
      }
    }, inviteuid)
  },

  

  //是否已关注
  //uid是关注者  fid是被关注者
  isFollow: function(uid, fid) {
      var that = this;
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"isaction",
            uid:uid,
            fid:fid
        },
        success:function(responseData){
            var data = responseData.data;
            if(data[0].rel == 2) {
                that.setData({
                    isFollow:true
                });
            }
        }
    });
  },
  //关注
  addFollow: function(e) {
    if (wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
      var that = this;
      var uid = e.currentTarget.dataset.uid;
      var fid = e.currentTarget.dataset.fid;
      var token = e.currentTarget.dataset.token;
      var privatekey = utilMd5.hexMD5(uid+'addaction'+token);
      util.api({
        data:{
            publickey:util.publiccode,
            ac:"addaction",
            uid:uid,
            tuid:fid,
            privatekey: privatekey
        },
        method:'POST',
        success:function(responseData){
            var data = responseData.data;
            if(data.res === true) {
                app.dialog('关注成功', 'success');
                that.setData({
                    isFollow: true
                });
            } else {
                app.dialog('关注失败', 'loading');
            }
        }
    });
  },
  //取消关注
  cancelFollow: function(e) {
    
      var that = this;
      var uid = e.currentTarget.dataset.uid;
      var fid = e.currentTarget.dataset.fid;
      var token = e.currentTarget.dataset.token;
      var privatekey = utilMd5.hexMD5(uid+'delaction'+token);
      util.api({
        data:{
            publickey:util.publiccode,
            ac:"delaction",
            uid:uid,
            tuid:fid,
            privatekey: privatekey
        },
        method:'POST',
        success:function(responseData){
            var data = responseData.data;
            if(data.res === true) {
                that.setData({
                    isFollow: false
                });
                app.dialog('取消关注成功', 'success');
            } else {
                app.dialog('取消关注失败', 'loading');
            }
        }
    });
  },
  //是否已赞
  isLike: function(uid) {
      var that = this;
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"isliketopic",
            uid:uid,
            topicid:topicid
        },
        success:function(responseData){
            var data = responseData.data;
            if(data.res === true) {
                that.setData({
                    isLiked: true
                });
            }
        }
    });
  },

  //赞列表
  getZanList: function () {
    var that = this;
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "topiclikeuser",
        topicid: that.data.data.id,
        cuid: uid,
        page: 1,
        num: 100
      },
      success: function (responseData) {
        var data = responseData.data;
        console.log("赞列表数据：", data);
        if (!data.msg) {
          that.setData({
            likeuser: data
          });
        } else {
          that.setData({
            likeuser: []
          });
        }
      }
    });
  },

  //赞
  addLike: function(e) {
    if(wxAuthFail){
      app.reAuthorize(this.reGetUserInfo);
      return;
    }

      var that = this;
      var uid = e.currentTarget.dataset.uid;
      var token = e.currentTarget.dataset.token;
      var privatekey = utilMd5.hexMD5(uid+'liketopic'+token);
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"liketopic",
            uid:uid,
            topicid:topicid,
            privatekey: privatekey
        },
        method:'POST',
        success:function(responseData){
            var data = responseData.data;
            console.log("赞动作结果：", data);
            if(data.res === true) {                
                that.setData({
                    isLiked: true
                });
                app.dialog('赞成功', 'success', that.getZanList());
            } else {
                app.dialog('赞失败', 'loading');
            }
        }
    });
  },
  //取消赞
  cancelLike: function(e) {
      var that = this;
      var uid = e.currentTarget.dataset.uid;
      var token = e.currentTarget.dataset.token;
      var privatekey = utilMd5.hexMD5(uid+'delliketopic'+token);
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"delliketopic",
            uid:uid,
            topicid:topicid,
            privatekey: privatekey
        },
        method:'POST',
        success:function(responseData){
            var data = responseData.data;
            if(data.res === true) {
                that.setData({
                    isLiked: false
                });
                app.dialog('取消赞成功', 'success', that.getZanList());                
            } else {
                app.dialog('取消赞失败', 'loading');
            }
        }
    });
  },
  //评论
  inputMessage: function(e) {
    //把评论内容绑定到提交按钮上
    var val = e.detail.value;
    this.setData({
        commentMsg: val
    })
  },
  changeReplyid: function(e) {
    var val = e.currentTarget.dataset.id;
    var replyusername = e.currentTarget.dataset.uname;
    this.setData({
        replyid: val,
        commentMsg:  '@回复'+replyusername +':'    
    })  
  },
  addComment: function(e) {
    if (wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }

      var that = this;
      var uid = e.currentTarget.dataset.uid;
      var token = e.currentTarget.dataset.token;
      var catatype = e.currentTarget.dataset.catatype;
      var replyid = e.currentTarget.dataset.replyid;      
      var message = e.currentTarget.dataset.message;
      if(!message) {
          app.dialog('请输入内容', 'loading');
          return;
      }
      var privatekey = utilMd5.hexMD5(uid+'topiccomment'+token);
    util.api({
        data:{
            publickey:util.publiccode,
            ac:"topiccomment",
            uid:uid,
            id:topicid,
            type:catatype,
            replyid:replyid,
            message:message,
            privatekey: privatekey
        },
        method:'POST',
        success:function(responseData){
            var data = responseData.data;
            var txt = replyid > 0 ? '回复':'评论';
            if(data.msg === "true") {                
                that.setData({
                    isLiked: true
                });
                that.setData({
                    commentMsg: ''
                })

                app.dialog(txt+'成功', 'success',that.refreshPage());
            } else {
                app.dialog(txt+'失败', 'loading');
            }
        }
    });
  },
  //投诉
  complain: function(e) {
      app.dialog('投诉成功', 'success');
  },
  //页面分享
  onShareAppMessage: function () {
    var invUid = this.data.uid? this.data.uid : '';
    var linkcode = this.data.data.linkcode ? this.data.data.linkcode : '';
    var path = '/pages/detail/detail?topicid=' + topicid + '&inviteuid=' + invUid + "&linkcode=" + linkcode;
    console.log("分享给好友：" + path); 
    return {
        title: topictitle?topictitle:uname,
        path: path
    };
  },

  copyLink:function(){
    var that = this;
    wx.setClipboardData({
      data: that.data.data.alt,
      success: function (res) {
        wx.showToast({
          title: '已复制到剪贴板',
        })
      }
    })
  },

  //分享朋友圈
  shareToPengyouquan: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log('海报图片链接：' + e.currentTarget.dataset.imgsrc);

    // shareImgUrl = base64.encode(shareImgUrl);
    // var url = "/pages/haibao-page/haibao-page?imgUrl=" + shareImgUrl;
    // wx.navigateTo({ url: url });
    
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  showEWM: function (e) {
    console.log('海报图片链接：' + e.currentTarget.dataset.imgsrc);
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: [e.currentTarget.dataset.imgsrc]
    })
  },
  //刷新当前页
  refreshPage: function() {
      wx.redirectTo({
          url:'/pages/detail/detail?topicid='+topicid
      })
  },

  //减少动作
  reduceAction: function (e) {
    var newInputValue = this.data.countValue - 1;
    if (newInputValue < 1) {
      return;
    }
    this.setData({
      countValue: newInputValue
    })
  },
  //增加动作
  addAction: function (e) {
    if (this.data.countValue >= this.data.data.kucun) {
      wx.showToast({
        title: '超出库存啦',
      });
      return;
    }
    var newInputValue = this.data.countValue + 1;
    this.setData({
      countValue: newInputValue
    })
  },

  buyAction: function(e){
    if (this.data.guigeData.length > 0 && !this.data.selectGuige){
      var toastStr = "请选择 " + this.data.data.guige; 
      wx.showModal({
        title: "提示",
        content: toastStr,
        showCancel: false
      })
    } else {
      var goodsInfo = {};
      goodsInfo.id = this.data.data.id;
      goodsInfo.ghsid = this.data.data.postuid;
      goodsInfo.title = this.data.data.topictitle;
      goodsInfo.def_img = this.data.data.photoscbk[0].photo;
      goodsInfo.sel = true;
      goodsInfo.guigeName = this.data.data.guige ? this.data.data.guige : '';
      goodsInfo.selGuige = this.data.selectGuige;
      if (this.data.data.pin == 1) {//拼单商品
        goodsInfo.price = this.data.data.pinprice;
      } else {
        goodsInfo.price = this.data.selectGuige ? this.data.selectGuige.price : this.data.data.sellprice;
      }
      goodsInfo.yunfei = this.data.data.yunfei;
      goodsInfo.kucun = this.data.data.kucun;
      goodsInfo.buycount = this.data.countValue;
      goodsInfo.source = this.data.data.source;
      goodsInfo.pin = this.data.data.pin;//这里加是否是拼单商品标记
      goodsInfo.pinzong = this.data.data.pinzong;//这个是拼单的 期数，通常一天为一个拼单周期
      goodsInfo.linkcode = this.data.data.linkcode;//商品唯一32位id

      var addItem = JSON.stringify([goodsInfo]);
      var url = "/pages/order-confirm/order-confirm?goodsArr=" + addItem;
      wx.navigateTo({ url: url});
    }
  },

  //加入购物车
  addToGouwuche:function(){
    if (this.data.guigeData.length > 0 && !this.data.selectGuige) {
      var toastStr = "请选择 " + this.data.data.guige;
      wx.showModal({
        title: "提示",
        content: toastStr,
        showCancel: false
      })
    } else {
      var gwc_datas = wx.getStorageSync('gwc_datas');
      if (!gwc_datas) {
        gwc_datas = [];
      }
      var goodsInfo = {};
      goodsInfo.id = this.data.data.id;
      goodsInfo.ghsid = this.data.data.postuid;
      goodsInfo.title = this.data.data.topictitle;
      goodsInfo.def_img = this.data.data.photoscbk[0].photo;
      goodsInfo.sel = true;
      goodsInfo.guigeName = this.data.data.guige ? this.data.data.guige : '';
      goodsInfo.selGuige = this.data.selectGuige;
      if (this.data.data.pin == 1) {//拼单商品
        goodsInfo.price = this.data.data.pinprice;
      } else {
        goodsInfo.price = this.data.selectGuige ? this.data.selectGuige.price : this.data.data.sellprice;
      }
      goodsInfo.yunfei = this.data.data.yunfei;
      goodsInfo.kucun = this.data.data.kucun;
      goodsInfo.buycount = this.data.countValue;
      goodsInfo.source = this.data.data.source;
      goodsInfo.pin = this.data.data.pin;//这里加是否是拼单商品标记
      goodsInfo.pinzong = this.data.data.pinzong;//这个是拼单的 期数，通常一天为一个拼单周期
      goodsInfo.linkcode = this.data.data.linkcode;//商品唯一32位id
      
      var addItem = [goodsInfo];
      var hasSameGoods = false;
      if(gwc_datas.length > 0){
        for(var i = gwc_datas.length - 1; i >= 0; i--){
          if(gwc_datas[i].id == goodsInfo.id){
            if(this.data.guigeData.length > 0){
              if (gwc_datas[i].selGuige.id == goodsInfo.selGuige.id){
                hasSameGoods = true;
                gwc_datas[i].buycount = gwc_datas[i].buycount + goodsInfo.buycount;
              }
            } else {
              hasSameGoods = true;
              gwc_datas[i].buycount = gwc_datas[i].buycount + goodsInfo.buycount;
            }
          }
        }
      }
      if(!hasSameGoods){
        gwc_datas = addItem.concat(gwc_datas);
        var count = this.data.gwc_count + 1;
        this.setData({
          gwc_count: count
        })
      }
      wx.setStorageSync('gwc_datas', gwc_datas);  
      var contentname = this.data.tc == 1 ? '已成功加到購物車' : '已成功加到购物车';
      wx.showToast({
        title: contentname,
      })
      // var confirmTextname = this.data.tc == 1 ? '去結算' : '去结算';
      // wx.showModal({
      //   title: '提示',
      //   content: contentname,
      //   cancelText: '再看看',
      //   confirmText: confirmTextname,
      //   success:function(res){
      //     if(res.confirm){
      //       wx.reLaunch({
      //         url: '/pages/gouwuche/gouwuche',
      //       })
      //     }
      //   }
      // })
    }
  },

  //跳转
  goAtherPage: function(e){
      var url = e.currentTarget.dataset.link;
      //如果是 立即购买 或 咨询 则需要判断是否已授权登录
      if (wxAuthFail && (url.indexOf('order-confirm') >= 0)){
        app.reAuthorize(this.reGetUserInfo);
        return;
      }

      var pageIndex = getCurrentPages().length;
      if(pageIndex >= 5){
        wx.redirectTo({ url: url, fail: function (e) { console.log(e) } })
      } else {
        wx.navigateTo({ url: url, fail: function (e) { console.log(e) } })
      }
  },
  // clickImg: function(e){
  //     this.setData({
  //         "stv.src":e.currentTarget.dataset.imgsrc,
  //         "stv.display":"true"
  //     });
  // },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },
  //跳转
  goAtherPageRelaunch: function (e) {
    var url = e.currentTarget.dataset.link;
    //如果是 立即购买 或 咨询 则需要判断是否已授权登录
    if (wxAuthFail && (url.indexOf('gouwuche/gouwuche') >= 0)) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
    wx.reLaunch({ url: url});
  },


  clickImg: function (e) {
    // this.setData({
    //     "stv.src":e.currentTarget.dataset.imgsrc,
    //     "stv.display":"true"
    // });
    var imgListType = e.currentTarget.dataset.imglist;
    var imgList = [];
    if (imgListType == "1"){
      var photo = this.data.data.photoscbk;
      for (var i = 0; i < photo.length ; i++){
        imgList = imgList.concat([photo[i].photo]);
      }
    } else if (imgListType == "2") {
      var photo = this.data.data.link_works;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat(photo[i].photosData);
      }
    } else if (imgListType == "3") {
      var photo = this.data.data.link_relations;
      for (var i = 0; i < photo.length; i++) {
        imgList = imgList.concat(photo[i].photosData);
      }
    }
    console.log(imgList);
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: imgList
    })
  },

  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path) {
      wx.redirectTo({ url: path })
    }
  },


  //删除数据
  delDataAction: function () {
    this.setData({
      modalHidden: false,
    })
  },

  modalBindaconfirm: function () {
    this.deleteData();
    this.setData({
      modalHidden: true,
    })
  },
  modalBindcancel: function () {
    this.setData({
      modalHidden: true
    })
  },

  deleteData: function () {

    var that = this;

    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var privatekey = utilMd5.hexMD5(uid + 'deltopic' + token);//私钥
    var ownerId = this.data.data.user.uid;
    var params = {
      ac: "deltopic",
      privatekey: privatekey,
      uid: ownerId,
      edituid: uid,
      topicid: that.data.data.id
    }
    console.log("deltopic params: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function (responseData) {

        var result = responseData.data;
        console.log("删除数据：", result);
        if (result.res) {
          app.dialogToast("删除成功", 'success', function () {
            // wx.reLaunch({
            //   url: '/pages/index/index',
            // })
            wx.navigateBack({
              delta:1
            })
          });
        }
      }
    });
  },

  setTopAction: function (e) {

    var that = this;
    var toastStr = "置顶成功";
    var uid = this.data.uid;//用户id
    var token = this.data.token;//用户token
    var level = 1;
    var ac = 'addtop';
    if (that.data.data.addtop >= 1) {
      ac = 'unaddtop';
      level = 0;
      toastStr = "已取消置顶";
    }
    var privatekey = utilMd5.hexMD5(uid + ac + token);//私钥
    var ownerId = this.data.data.user.uid;
    var params = {
      ac: ac,
      privatekey: privatekey,
      uid: ownerId,
      edituid: uid,
      id: that.data.data.id,
      level: level
    }
    
    params.ac = ac;

    console.log("置顶／取消置顶 params: ", params);
    util.api({
      method: "POST",
      data: params,
      success: function (responseData) {

        var result = responseData.data;
        console.log(toastStr, result);
        if (result.res) {
          app.dialogToast(toastStr, 'success');
          var detailData = that.data.data;
          detailData.addtop = level;
          that.setData({
            data: detailData
          })
        }
      }
    });
  },

  editDataAction: function () {
    var that = this;
    var topicType = that.data.data.topictype;
    var pageUrl = '';
    var topicData = base64.encode(JSON.stringify(that.data.data));
    // console.log("要修改的数据：", topicData);
    if (topicType == 4){//商品
      pageUrl = "/pages/release-goods/release-goods?data=" + topicData;
    } else if (topicType == 6) {//作品
      pageUrl = "/pages/release-zp/release-zp?data=" + topicData;
    } else if (topicType == 7 || topicType == 2) {//相册／动态
      pageUrl = "/pages/release-jk/release-jk?data=" + topicData;
    } else if (topicType == 8) {//展览
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 9) {//文字
      pageUrl = "/pages/release-wz/release-wz?data=" + topicData;
    } else if (topicType == 11) {//视频
      pageUrl = "/pages/release-sp/release-sp?data=" + topicData;
    } else if (topicType == 13) {//艺术年表
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 14) {//荣誉奖项
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 15) {//收藏拍卖
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 16) {//公益捐赠
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    } else if (topicType == 17) {//媒体
      pageUrl = "/pages/release-mt/release-mt?data=" + topicData;
    } else if (topicType == 18) {//出版刊登
      pageUrl = "/pages/release-jj/release-jj?data=" + topicData;
    }

    if (pageUrl) {
      var pages = getCurrentPages();
      var curPageIndex = pages.length;
      if(curPageIndex >= 5){
        wx.redirectTo({
          url: pageUrl,
        })
      } else {
        wx.navigateTo({
          url: pageUrl,
        })
      }
      
    }
  },

  getGuigeData: function (g_id) {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "goodsguige",
        "goods_id": g_id
      },
      success: function (responseData) {
        console.log("商品规格：", responseData.data)
        if (!responseData.data.msg) {
          var selGuige = responseData.data[0];
          that.setData({
            guigeData: responseData.data,
            selectGuige: selGuige
          })
        }
      }
    });
  },

  guigeSelect: function (e) {
    var selGuige = e.currentTarget.dataset.data;

    this.setData({
      // actionSheetHidden: !this.data.actionSheetHidden,
      selectGuige: selGuige,
      allprice: (this.data.buynum * (selGuige.price / 100)).toFixed(2),
      oneprice: (selGuige.price / 100).toFixed(2)
    })
  },

  showEWMAV: function (e) {
    wx.previewImage({
      current: e.currentTarget.dataset.imgsrc,
      urls: [e.currentTarget.dataset.imgsrc]
    })
  },

  makeCallPhone: function (e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },


  //获取运费设置
  getYunfeiSet: function () {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "xsdyunfei",
        "binduid": util.orgid
      },
      success: function (responseData) {
        console.log("运费：", responseData);
        var data = responseData.data;
        that.setData({
          my_cion: parseInt(data.mianfei),
        })
      }
    });
  },
})